package com.xh.hongaicodegenerator.langgraph4j.node;

import com.xh.hongaicodegenerator.ai.AiCodeRoutingTypeService;
import com.xh.hongaicodegenerator.ai.AiCodeRoutingTypeServiceFactory;
import com.xh.hongaicodegenerator.langgraph4j.model.enums.TemplateTypeEnum;
import com.xh.hongaicodegenerator.langgraph4j.state.WorkflowContext;
import com.xh.hongaicodegenerator.model.enums.CodeGenTypeEnum;
import com.xh.hongaicodegenerator.monitor.FluxContext;
import com.xh.hongaicodegenerator.monitor.MonitorContextHolder;
import com.xh.hongaicodegenerator.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.bsc.langgraph4j.action.AsyncNodeAction;
import org.bsc.langgraph4j.prebuilt.MessagesState;

import static org.bsc.langgraph4j.action.AsyncNodeAction.node_async;

/**
 * 智能路由工作节点
 */
@Slf4j
public class RouterNode {

    public static AsyncNodeAction<MessagesState<String>> create() {
        return node_async(state -> {
            WorkflowContext context = WorkflowContext.getContext(state);
            log.info("执行节点: 智能路由");
            TemplateTypeEnum templateType=context.getTemplateTypeEnum();
            if (templateType == null){
                try {
                    // 获取AI路由服务
                    AiCodeRoutingTypeServiceFactory factory = SpringContextUtil.getBean(AiCodeRoutingTypeServiceFactory.class);
                    AiCodeRoutingTypeService routingService = factory.createAiCodeGenTypeRoutingService();
                    // 根据原始提示词进行智能路由
                    templateType = routingService.routeTemplateType(context.getOriginalPrompt()+"\n帮我选择最合适的模板代码\n");
                    log.info("AI智能路由完成，选择类型: {} ({})", templateType.getValue(), templateType.getText());
                } catch (Exception e) {
                    log.error("AI智能路由失败，不使用模板代码: {}", e.getMessage());
                    templateType = TemplateTypeEnum.WITHOUT_TEMPLATE;
                }
            }
            context.setTemplateTypeEnum(templateType);
            // 更新状态
            context.setCurrentStep("智能路由");
            Integer stepCount = context.getStepCount()+1;
            context.setStepCount(stepCount);
            FluxContext flux= MonitorContextHolder.getFlux();
            flux.getSink().next(String.format("\n\n第 %s 步 %s 执行完成，选择模板：%s \n\n",stepCount,"智能路由",templateType.getText()));
            return WorkflowContext.saveContext(context);
        });
    }
}